<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <meta name="description" content="Write an awesome description
		for your new site here. You can edit this line in _config.yml.
		It will appear in your document head meta (for Google search results)
		and in your feed.xml site description.
		">
    <title>上传成绩及图片</title>

    <link rel="stylesheet" href="../lib/weui.min.css">
    <link rel="stylesheet" href="../css/jquery-weui.css">
    <link rel="stylesheet" href="../css/demos.css">
    <script src="../lib/jquery-2.1.4.js"></script>
    <script src="../lib/fastclick.js"></script>
    <script src="../js/jquery-weui.js"></script>
    <script src="../js/weui.min.js"></script>
    <script src="../js/layer.js" charset="utf-8"></script>
</head>
<body>
<header class='demos-header'>
    <h2 class="demos-second-title">上传成绩及图片</h2>
</header>
<div class="weui-cells weui-cells_form">
    <input hidden id="eventBeginTime" value="${eventBeginTime}"/>
    <div class="weui-cell">
        <div class="weui-cell__hd"><label for="event_price_id" class="weui-label">赛事名称</label></div>
        <div class="weui-cell__bd">
            <input class="weui-input" type="text" value="${eventName}" readonly="" id="event_id"
                   name="event_id">
            <input type="hidden" name="eventId" value="${eventId}"/>
        </div>
    </div>

    <div class="weui-cell">
        <div class="weui-cell__hd"><label for="code" class="weui-label">参赛号</label></div>
        <div class="weui-cell__bd">
            <input class="weui-input" type="text" placeholder="请输入参赛号" id="code" maxlength="100"
                   name="code"/>
        </div>
    </div>
    <div class="weui-cell">
        <div class="weui-cell__hd"><label for="finalDistance" class="weui-label">项目距离</label></div>
        <div class="weui-cell__bd">
            <input class="weui-input" type="text" placeholder="最终距离(km)" id="finalDistance" maxlength="100"
                   name="finalDistance" readonly/>
        </div>
    </div>
    <div class="weui-cell">
        <div class="weui-cell__hd"><label for="finalResult" class="weui-label">参赛用时</label></div>
        <div class="weui-cell__bd">
            <input class="weui-input" type="text" placeholder="(例如) 1:29:59" id="finalResult" maxlength="100"
                   name="finalResult"/>
        </div>
    </div>




    <div class="weui-cell">
        <div class="weui-cell__bd">
            <div class="weui-uploader">
                <div class="weui-uploader__hd">
                    <p class="weui-uploader__title">成绩截图上传:</p>
                    <div class="weui-uploader__info"><span id="uploadCount">0</span>/4</div>
                </div>
                <p class="weui-uploader__title" style="font-size: 14px;color: red;margin-bottom:0.5rem;">
                    大小不能超过5M</p>
                <div class="weui-uploader__bd">
                    <ul class="weui-uploader__files" id="uploaderFiles">
                    </ul>
                    <div class="weui-uploader__input-box">
                        <input id="uploaderInput" class="weui-uploader__input" type="file"
                               accept="image/jpg,image/jpeg,image/png,image/gif" multiple="">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="weui-gallery" id="gallery">
    <span class="weui-gallery__img" id="galleryImg"></span>
    <div class="weui-gallery__opr">
        <a href="javascript:" class="weui-gallery__del">
            <i class="weui-icon-delete weui-icon_gallery-delete"></i>
        </a>
    </div>
</div>
<div class="weui-btn-area">
    <a class="weui-btn weui-btn_primary" href="javascript:" id="next">提交</a>
</div>
</body>
<script>

    $(document).ready(function () {
        $("#code").focus();
        var eventBeginTime = $("#eventBeginTime").val()
        let beginParse = Date.parse(eventBeginTime);

        if (Date.now() < beginParse) {
            alert("功能暂未到开放时间，请完赛后再继续");
            var userAgent = navigator.userAgent;
            if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Chrome") != -1) {
                document.addEventListener('WeixinJSBridgeReady', function () {
                    WeixinJSBridge.call('closeWindow');
                }, false)
            } else {
                setTimeout(function () {
                    WeixinJSBridge.invoke("closeWindow", {}, function (e) {
                    })
                }, 100)
            }
            return false;
        }

    });

    function validate(param) {
        if (param.code == "") {
            $.toptip('警告,参赛码不能为空', 'warning');
            return false;
        }
        if (param.finalResult == "") {
            $.toptip('警告,最终时间不能为空', 'warning');
            return false;
        }
        if (param.finalDistance == "") {
            $.toptip('警告,最终距离不能为空', 'warning');
            return false;
        }
        if (param.pic == "") {
            $.toptip('警告,图片不能为空', 'warning');
            return false;
        }
        let split = param.finalResult.split(":");
        if (split.length<=1){
            $.toptip('警告,输入的参赛用时不符合规范', 'warning');
            return false;
        }
        let splitElement = split[0];

        if ("21.0975KM" == param.finalDistance) {
            if (splitElement * 1 >= 3) {
                $.toptip('警告,半马不能多于3小时', 'warning');
                return false;
            }
        }
        if ("42.195KM" == param.finalDistance) {
            if (splitElement * 1 >= 6) {
                $.toptip('警告,全马不能多于6小时', 'warning');
                return false;
            }
        }
        if ("63.3KM" == param.finalDistance) {
            if (splitElement * 1 >= 9) {
                $.toptip('警告,超马不能多于9小时', 'warning');
                return false;
            }
        }


        return true;
    }

    var param = {};
    var picList = [];


    $("#code").change(function () {
        $.ajax({
            url: "/get/race/group/part/code?eventId=${eventId}&code=" + $("#code").val(),
            method: "post",
            dataType: "json",
            async: false,
            contentType: "application/json",
            success: function (res) {
                if (res.status == 1) {
                    $("#finalDistance").val(res.data);
                    if ("63.3KM" == res.data) {
                        $("#finalResult").attr("placeholder", "(例如) 5:59:59")
                    } else if ("21.0975KM" == res.data) {
                        $("#finalResult").attr("placeholder", "(例如) 1:29:59")
                    } else if ("42.195KM" == res.data) {
                        $("#finalResult").attr("placeholder", "(例如) 3:29:59")
                    }
                }
                else {
                    alert(res.msg);
                }
            }
        })
    })

    $("#next").click(function () {

        param.eventId = ${eventId};
        param.code = $("#code").val();
        param.finalResult = $("#finalResult").val();
        param.finalDistance = $("#finalDistance").val();
        param.pic = "";
        for (let i = picList.length - 1; i >= 0; i--) {
            let content = picList[i];

            $.ajax({
                url: "/putDataBase64Jpg",
                method: "post",
                dataType: "json",
                async: false,
                contentType: "application/json",
                data: JSON.stringify({"content": content}),
                success: function (res) {
                    param.pic = param.pic + res.data + ','
                }
            })
        }

        if (validate(param)) {
            var loading = layer.load(1, {
                shade: [0.5, '#fff'],
            });
            $.ajax({
                url: "/participant/update/best/score/pic",
                method: "post",
                dataType: "json",
                async: true,
                contentType: "application/json",
                data: JSON.stringify(param),
                success: function (res) {
                    layer.close(loading);
                    $.hideLoading();
                    alert(res.msg);
                    var userAgent = navigator.userAgent;
                    if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Chrome") != -1) {
                        document.addEventListener('WeixinJSBridgeReady', function () {
                            WeixinJSBridge.call('closeWindow');
                        }, false)
                    } else {
                        setTimeout(function () {
                            WeixinJSBridge.invoke("closeWindow", {}, function (e) {
                            })
                        }, 100)
                    }
                    return false;
                }
            })
            layer.close(loading);
        }
        layer.close(loading);
        $.hideLoading();
    })

    // 允许上传的图片类型
    var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
    var maxSize = 1024 * 1024 * 5; // 10240KB，也就是 5MB
    var maxWidth = 1900;  // 图片最大宽度
    var maxCount = 1;// 最大上传图片数量

    //
    var tmpl = '<li class="weui-uploader__file" id="#ImgID#" style="background-image:url(#url#)"><div class="weui_uploader_status_content" style="color:red">0%</div></li>',
            $gallery = $("#gallery"),
            $galleryImg = $("#galleryImg"),
            $uploaderInput = $("#uploaderInput"),
            $uploaderFiles = $("#uploaderFiles");


    var picList = [];

    $uploaderInput.on("change", function (e) {
        files = e.target.files;
        // 如果没有选中文件，直接返回
        if (files.length === 0) {
            return;
        }
        for (var i = 0, len = files.length; i < len; ++i) {
            var file = files[i];
            var imgID = genGUID();
            var reader = new FileReader();
            var fileType = file.type;
            // 如果类型不在允许的类型范围内
            if (allowTypes.indexOf(file.type) === -1) {

                $.toast('该类型不允许上传' + fileType, "forbidden");
                continue;
            }

            if (file.size > maxSize) {
                $.toast("图片太大，不允许上传", "forbidden");
                continue;
            }

            if ($('.weui-uploader__file').length >= maxCount) {
                $.toast('最多只能上传' + maxCount + '张图片', "forbidden");
                return;
            }


            reader.onload = function (e) {
                var img = new Image();
                img.onload = function () {
                    // 不要超出最大宽度
                    var w = Math.min(maxWidth, img.width);
                    // 高度按比例计算
                    var h = img.height * (w / img.width);
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    // 设置 canvas 的宽度和高度
                    canvas.width = w;
                    canvas.height = h;
                    ctx.drawImage(img, 0, 0, w, h);
                    var base64 = canvas.toDataURL(fileType, 0.6); //0.6指的是压缩60%

                    // 插入到预览区
                    $uploaderFiles.append($(tmpl.replace('#url#', base64).replace('#ImgID#', imgID)));

                    var num = $('.weui-uploader__file').length;
                    $('#uploadCount').text(num);

                    // 模拟上传进度
                    var progress = 0;

                    function uploading() {
                        $uploaderFiles.find('.weui_uploader_status_content').text(++progress + '%');
                        if (progress < 100) {
                            setTimeout(uploading, 30);
                        } else {
                            $uploaderFiles.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();//清除上传进度图标
                        }
                    }

                    setTimeout(uploading, 30);
                };

                img.src = e.target.result;
                picList.push(e.target.result)

            };
            reader.readAsDataURL(file);

        }
    });


    var index; //第几张图片
    $uploaderFiles.on("click", "li", function () {
        index = $(this).index();
        $galleryImg.attr("style", this.getAttribute("style"));
        $gallery.fadeIn(100);
    });
    $gallery.on("click", function () {
        $gallery.fadeOut(100);
    });

    //删除图片
    $(".weui-gallery__del").click(function () {
        console.log(picList);
        console.log(index);
        $uploaderFiles.find("li").eq(index).remove();
        picList.splice(index, 1);
        var num = $('.weui-uploader__file').length;
        $('#uploadCount').text(num);
        console.log(picList)
    });

    //生成guid
    function genGUID() {
        var G1 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        var G2 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        return (G1 + G2);
    }
</script>
</html>